﻿using System;
using System.Windows;
using System.Windows.Threading;

namespace SipCompensation
{
    internal class ClipboardMonitor : IDisposable
    {
        private readonly DispatcherTimer _timer;

        public event Action ClipboardTextChanged = delegate {  };

        public ClipboardMonitor()
        {
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromMilliseconds(250);
            _timer.Tick += TimerOnTick;
            _timer.Start();
        }

        private void TimerOnTick(object sender, EventArgs eventArgs)
        {
            try
            {
                if (Clipboard.ContainsText())
                {
                    ClipboardTextChanged();
                    _timer.Stop();
                }
            }
            catch (Exception)
            {
                // Random COMExceptions are thrown. Nothing can be done. It is a known issue in .NET
            }
        }

        public void Dispose()
        {
            _timer.Stop();
            _timer.Tick -= TimerOnTick;
        }
    }
}